import React, { useEffect, useRef, useState } from 'react'
import { Table, Switch, Button, Modal, Popconfirm } from 'antd';
import axios from 'axios';
import UserModalList from '../../../components/user-list/UserModalList';


export default function UserList() {
  const [dataSource, setdataSource] = useState([])
  const [regionList, setregionList] = useState([])
  const [roleList, setroleList] = useState([])
  const [open, setOpen] = useState(false);
  const [updateOpen, setupdateOpen] = useState(false);
  const [sonDisabled, setsonDisabled] = useState(false)
  const [current, setcurrent] = useState('')


  const addForm = useRef(null)
  const updateForm = useRef(null)

  const { roleId, region, username } = JSON.parse(localStorage.getItem('token'))
  // 表格数据
  useEffect(() => {
    axios.get('/users?_expand=role').then(res => {
      const list = res.data
      setdataSource(roleId === 1 ? list : [
        ...list.filter(item => item.username === username),
        ...list.filter(item => item.region === region && item.roleId === 3)
      ])
    })
  }, [roleId, region, username])
  // 区域数据
  useEffect(() => {
    axios.get('/regions').then(res => {
      // console.log(res)
      setregionList(res.data)
    })
  }, [])
  // 角色数据
  useEffect(() => {
    axios.get('/roles').then(res => {
      // console.log(res)
      setroleList(res.data)
    })
  }, [])

  // 改变开关状态
  const changeSwitch = (item) => {
    // console.log(item)
    item.roleState = !item.roleState
    setdataSource([...dataSource])
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
  }

  // 确定提交表单
  const addModalForm = () => {
    // 表单验证
    addForm.current.validateFields().then(value => {
      setOpen(false)
      addForm.current.resetFields()
      axios.post('/users', {
        ...value,
        default: false,
        roleState: true
      }).then(res => {
        setdataSource([...dataSource, {
          ...res.data,
          role: roleList.filter(item => item.id === value.roleId)[0]
        }])
      })
    }).catch(err => {
      console.log(err)
    })

  }
  // 删除
  const deleteItem = (item) => {
    // console.log(item)
    // 先使页面同步
    setdataSource(dataSource.filter(data => item.id !== data.id))
    // 再使后端同步
    axios.delete(`/users/${item.id}`)
  }

  // 编辑按钮
  const updateButton = (item) => {
    console.log(item)
    setcurrent(item)
    setupdateOpen(true)
    if (item.roleId === 1) {
      setsonDisabled(true)
    } else {
      setsonDisabled(false)
    }
    // 解决出现打开form后数据未显示的问题
    setTimeout(() => {
      updateForm.current.setFieldsValue(item)
    }, 0)
  }


  // 确定更新编辑
  const updateModalForm = () => {
    updateForm.current.validateFields().then(value => {
      setupdateOpen(false)
      setdataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(item => item.id === value.roleId)[0]
          }
        }
        return item
      }))
      axios.patch(`/users/${current.id}`, value)
    })
  }
  // 表格数据
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [...regionList.map(item => {
        return {
          text: item.title,
          value: item.value
        }
      }), { text: '全球', value: '全球' }],
      onFilter: (value, record) => {
        if (value === '全球') {
          return record.region === ''
        }
        return record.region.indexOf(value) === 0
      },
      render: (region) => {
        return <b>{region === '' ? '全球' : region}</b>
        // 全球返回的是""空字符串需要判断
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role.roleName
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      // 第二个参数传的是所有
      render: (roleState, item) => <Switch checked={roleState} disabled={item.default ? true : ''} onChange={() => changeSwitch(item)}></Switch>
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="删除"
            description="你确定要删除吗"
            onConfirm={() => deleteItem(item)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='primary' danger disabled={item.default ? true : ''}>删除</Button>
          </Popconfirm>
          <Button type='primary' disabled={item.default ? true : ''} onClick={() => updateButton(item)}>修改</Button>
        </div>
      }
    },
  ];
  return (
    <div>
      <Button type='primary' onClick={() => setOpen(true)}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns} rowKey={(record) => record.id} pagination={{ pageSize: 5 }} />
      {/* 添加用户 */}
      <Modal
        open={open}
        title="添加用户"
        okText="确认"
        cancelText="取消"
        onCancel={() => setOpen(false)}
        onOk={() => addModalForm()}
      >
        {/* 对话框表单组件 */}
        <UserModalList regionList={regionList} roleList={roleList} ref={addForm}></UserModalList>
      </Modal>


      {/* 修改用户 */}
      <Modal
        open={updateOpen}
        title="修改用户"
        okText="确认"
        cancelText="取消"
        onCancel={() => {
          setupdateOpen(false)
          setsonDisabled(!sonDisabled)
        }}
        onOk={() => updateModalForm()}
      >
        {/* 对话框表单组件 */}
        <UserModalList isUpdate={true} regionList={regionList} roleList={roleList} ref={updateForm} dadDisabled={sonDisabled}></UserModalList>
      </Modal>

    </div >
  )
}
